AJAX เสถ ยร ห นตา ส าน กเทคโนโลย สารสนเทศและการส อสาร มหาว ทยาล ยนเรศวร พะเยา 1
Ajax ( Asynchronous JavaScript and XML ) Ajax ค ออะไร JavaScript DHTML = Dynamic HTML XML = Extensive Markup Language Css = Cascading Style Sheets Dom = Document Object Model XMLHTTPRequest 2
โครงสร างของ Ajax จากรป Ajax engine น อยระ หยาง วser UnterIace กf server บซ ง จะองหยาปม ปมนการเ นการเ างานเ Client การเ างานทยาง ของ ต ต โปรๆกร จะไป ร ก Ajax engine ทfหน ขซน า ๆเ นเ การร องขอ น า หม จาก server โผ ทรง 3
ข อผ ของ Ajax update ๆ างสยหน ทใผทยอๆ Asynchronous ประ หช ชเ Server ชผชง รองรf ราห บอรแ ชfก ชfก JavaScript ไ ยท องทใผทfง ร อ ต Plugs in 4
ทfหอ ยาง หม ๆ Ajax mail mail indos Live s Live Hotmail 5
AJAX AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page. AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly. 6
To get or send information from/to a database or a file on the server with traditional JavaScript, you will have to make an HTML form, and a user will have to click the "Submit" button to send/get the information, wait for the server to respond, then a new page will load with the results. Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly. With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object. With the XMLHttpRequest object, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background. 7
XMLHttpRequest By using the XMLHttpRequest object, a web developer can update a page with data from the server after the page has loaded! AJAX was made popular in 2005 by Google (with Google Suggest). Google Suggest is using the XMLHttpRequest object to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions. The XMLHttpRequest object is supported in all major browsers (Internet Explorer, Firefox, Chrome, Opera, and Safari). 8
Browser and AJAX All new browsers support a new built-in JavaScript XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject). This object can be used to request information (data) from a server. Let's update our HTML file with a JavaScript in the <head> section: 9
function loadxmldoc(url) if (window.xmlhttprequest) // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); else // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("get",url,false); xmlhttp.send(null); document.getelementbyid('test').innerhtml=xmlhtt p.responsetext; 10
Important Methods The XMLHttpRequest object has 2 important methods: The open() method The send() method 11
Sending an AJAX Request to a Server To send a request to a web server, we use the open() and send() methods. The open() method takes three arguments. The first argument defines which method to use (GET or POST). The second argument specifies the name of the server resource (URL). The third argument specifies if the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that requested a file called "time.asp", the code would be: url="time.asp" xmlhttp.open("get",url,true); xmlhttp.send(null); In the example we assume that the current web page and the requested resource are both in the same file directory. 12
Important Properties The XMLHttpRequest object has 3 important properties: The responsetext property The readystate property The onreadystatechange property 13
The responsetext property The XMLHttpRequest object stores any data retrieved from a server as a result of a server request in its responsetext property. In the previous chapter we copied the content of the responstext property into our HTML with the following statement: document.getelementbyid('test').innerhtml=xmlh ttp.responsetext 14
XMLHttpRequest Open - Using False xmlhttp.open("get",url,false); xmlhttp.send(null); document.getelementbyid('test').innerhtml=xmlhttp.respo nsetext; The third parameter in the open call is "false". This tells the XMLHttpRequest object to wait until the server request is completed before next statement is executed. For small applications and simple server request, this might be OK. But if the request takes a long time or cannot be served, this might cause your web application to hang or stop. 15
XMLHttpRequest Open - Using True By changing the third parameter in the open call to "true", you tell the XMLHttpRequest object to continue the execution after the request to the server has been sent. Because you cannot simply start using the response from the server request before you are sure the request has been completed, you need to set the onreadystatechange property of the XMLHttpRequest, to a function (or name of a function) to be executed after completion. In this onreadystatechange function you must test the readystate property before you can use the result of the server call. Simply change the code to: xmlhttp.onreadystatechange=function() if(xmlhttp.readystate==4) document.getelementbyid('test').innerhtml=xmlhttp.response Text xmlhttp.open("get",url,true); xmlhttp.send(null); 16
The readystate property The readystate property holds the status of the server's response. Possible values for the readystate property: 17
The onreadystatechange property The onreadystatechange property stores a function (or the name of a function) to be called automatically each time the readystate property changes. You can store a full function in the property like this: xmlhttp.onreadystatechange=function() if(xmlhttp.readystate==4) document.getelementbyid('test').innerhtml=xmlhttp.res ponsetext xmlhttp.open("get",url,true); xmlhttp.send(null); 18
Or you can store the name of a function like this: xmlhttp.onreadystatechange=state_change xmlhttp.open("get",url,true); xmlhttp.send(null);......... function state_change() if(xmlhttp.readystate==4) document.getelementbyid('test').innerhtml=xmlhttp.res ponsetext 19
XMLHttpRequest Object can Request any Data With the XMLHttpRequest object, you can request any web resource from a server. You can request TXT files, HTML files, XML files, pictures or any data that is accessible from the Internet. 20
Example explained - The HTML form <form> First Name: <input type="text" id="txt1" onkeyup="showhint(this.value)" /> </form> <p>suggestions: <span id="txthint"></span></p> 21
var xmlhttp function showhint(str) if (str.length==0) document.getelementbyid("txthint").innerhtml=""; return; xmlhttp=getxmlhttpobject(); if (xmlhttp==null) alert ("Your browser does not support XMLHTTP!"); return; var url="gethint.php"; url=url+"?q="+str; url=url+"&sid="+math.random(); xmlhttp.onreadystatechange=statechanged; xmlhttp.open("get",url,true); xmlhttp.send(null); 22
The function above executes every time a character is entered in the input field. If there is input in the input field (str.length > 0), the showhint() function executes the following: Defines the URL (filename) to send to the server Adds a parameter (q) to the URL with the content of the input field Adds a random number to prevent the server from using a cached file Creates an XMLHTTP object, and tells the object to execute a function called statechanged when a change is triggered Opens the XMLHTTP object with the given URL Sends an HTTP request to the server 23
The GetXmlHttpObject() function function GetXmlHttpObject() if (window.xmlhttprequest) // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); if (window.activexobject) // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); return null; 24
The statechanged() function function statechanged() if (xmlhttp.readystate==4) document.getelementbyid("txthint").innerh TML=xmlhttp.responseText; 25
The AJAX JavaScript function statechanged() if (xmlhttp.readystate==4) document.getelementbyid("txthint").innerhtml=xmlhttp.responsetext; function GetXmlHttpObject() if (window.xmlhttprequest) // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); if (window.activexobject) // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); return null; 26
PHP <?php // Fill up array with names $a[]="anna"; $a[]="brittany"; $a[]="cinderella"; $a[]="diana"; $a[]="eva"; $a[]="fiona"; $a[]="gunda"; 27
//get the q parameter from URL $q=$_get["q"]; //lookup all hints from array if length of q>0 if (strlen($q) > 0) $hint=""; for($i=0; $i<count($a); $i++) if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) if ($hint=="") $hint=$a[$i]; else $hint=$hint.", ".$a[$i]; 28
// Set output to "no suggestion" if no hint were found // or to the correct values if ($hint == "") $response="no suggestion"; else $response=$hint; //output the response echo $response;?> 29
Step of AJAX สร างอ อบเจ ก XMLHttpRequest ตรวจสอบสถานะจาก property onreadystatechange หากคาจาก property readystate เทากบ 4 กให น าผลล พธ ท ตอบ กล บมา(property responsetext ) ไใป ช เลย สง request ไย ง Server 30
AJAX and Database 31
HTML Code <html> <head> <script type="text/javascript" src="selectcustomer.js"></script> </head> <body> <form> Select a Customer: <select name="customers" onchange="showcustomer(this.value)"> <option value="alfki">alfreds Futterkiste</option> <option value="norts ">North/South</option> <option value="wolza">wolski Zajazd</option> </select> </form> <div id="txthint"><b>customer info will be listed here.</b></div> </body> </html 32
JavaScript selectcustomer.js var xmlhttp function showcustomer(str) xmlhttp=getxmlhttpobject(); if (xmlhttp==null) alert ("Your browser does not support AJAX!"); return; var url="getcustomer.asp"; url=url+"?q="+str; url=url+"&sid="+math.random(); xmlhttp.onreadystatechange=statechanged; xmlhttp.open("get",url,true); xmlhttp.send(null); 33
function statechanged() if (xmlhttp.readystate==4) document.getelementbyid("txthint").innerhtml=xmlhttp.responsetex t; function GetXmlHttpObject() if (window.xmlhttprequest) // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); if (window.activexobject) // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); return null; 34
Server Page getcustomer.asp <% response.expires=-1 sql="select * FROM CUSTOMERS WHERE CUSTOMERID=" sql=sql & "'" & request.querystring("q") & "'" set conn=server.createobject("adodb.connection") conn.provider="microsoft.jet.oledb.4.0" conn.open(server.mappath("/db/northwind.mdb")) set rs=server.createobject("adodb.recordset") rs.open sql,conn response.write("<table>") do until rs.eof for each x in rs.fields response.write("<tr><td><b>" & x.name & "</b></td>") response.write("<td>" & x.value & "</td></tr>") next rs.movenext loop response.write("</table>") %> 35
อ างอ ง www.w3schools.com บ ดปา ไะส ละเตส ง. พ ญนาเวบช วยเทคน ค Ajax และ PHP. กรฒงเทพ : บร ฯ ท ว.พร นท ษ (1991) จ ากช, 2551 36